package com.hqyj.service.impl;

import com.github.qcloudsms.httpclient.HTTPException;
import com.hqyj.dao.EmployeeMapper;
import com.hqyj.dao.UserMapper;
import com.hqyj.pojo.Employee;
import com.hqyj.pojo.User;
import com.hqyj.service.LoginService;
import com.hqyj.util.EmailUtil;
import com.hqyj.util.MyMdFive;
import com.hqyj.util.Phone;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

@Service
public class LoginServiceImpl implements LoginService {

    //拿到dao层接口对象
    @Autowired
    UserMapper Umapper;

    //拿到员工dao层对象
    @Autowired
    EmployeeMapper Emapper;

    //拿到工具类对象
    @Autowired
    MyMdFive myMdFive;

    //拿到邮箱工具类对象
    @Autowired
    EmailUtil emailUtil;

    //登录验证
    public HashMap<String, Object> loginShiro(User user) {
        //创建map集合，响应给前端信息
        HashMap<String, Object> map = new HashMap<String, Object>();
        //获取令牌，拿到用户名和密码
        UsernamePasswordToken token = new UsernamePasswordToken(user.getuNumber(),user.getuPassword());
        System.out.println(user.getuNumber()+user.getuPassword());
        //获取shiro用户对象
        Subject subject = SecurityUtils.getSubject();
        try{
            //登录
            subject.login(token);
            //如果没有捕捉到异常，那么登录成功
            map.put("info","登录成功");
            //拿到登录用户对象
            try{
                //拿到客户对象
                User user1 =(User) subject.getPrincipal();
                //返回用户ID给前端
                map.put("userId",user1.getuId());
                //告诉前端是客户
                map.put("iinfo","user");
            }catch (Exception e){
                //拿到员工对象
                Employee employee = (Employee) subject.getPrincipal();
                //返回员工ID给前端
                map.put("empId",employee.getEmployeeId());
                //返回前端告诉前台是员工
                map.put("iinfo","emp");
            }

        }catch (UnknownAccountException u){
            map.put("info","您输入的用户名不存在！");
        }catch (IncorrectCredentialsException io){
            map.put("info","您输入的密码不正确！");
        }
        return map;
    }

    //注册查询是否重名
    public HashMap<String, Object> repeatRegister(String userNumber) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //调用接口方法查询该用户账号是否重名
        String str = Umapper.selectByUserNumber(userNumber);
        Employee e = Emapper.selectByEmployeeName(userNumber);

        //如果为空则没有重名，返回空字符串，前端可不用清空span标签内容
        if(str==null&&e==null){
            map.put("info","");
        }else {
            //重名则返回信息
            map.put("info","该用户账号已被注册，请重新输入！");
        }
        return map;
    }

    //注册新用户
    public HashMap<String, Object> register(User user) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //给新用户的密码加密
        user.setuPassword(myMdFive.encrypt(user.getuPassword(),user.getuNumber()));
        //向数据库插入新数据
        int i = Umapper.insert(user);
        if(i>0){
            map.put("info","注册成功！");
            //如果绑定了邮箱，则同时给邮箱发送注册成功的信息
            if(user.getuEmail()!=null){
                emailUtil.send(user.getuEmail(),"尊敬的："+user.getuName()+"恭喜您绑定邮箱注册成功！世际酒店欢迎您，我们每日都会有优惠活动，敬请期待","恭喜您成为世际酒店会员");
            }
        }else {
            map.put("info","注册失败！");
        }
        return map;
    }

    //邮箱发送验证码
    public HashMap<String, Object> sendEmail(String uEmail, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //生成6位随机数验证码
        Random rd = new Random();
        int code = rd.nextInt(999999);
        //把验证码存入到session中
        HttpSession session = request.getSession();
        session.setAttribute("code",code);
        //发送验证码
        boolean is = emailUtil.send(uEmail,"您的验证码为："+code,"世纪酒店发送验证码");
        if(is){
            map.put("info","发送成功");
        }else {
            map.put("info","发送失败");
        }
        return map;
    }

    //绑定邮箱验证
    public HashMap<String, Object> registerEmail(String code, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //取出session中存的验证码
        HttpSession session = request.getSession();
        String sCode = session.getAttribute("code")+"";
        if(code.equals(sCode)){
            map.put("info","验证成功");
        }else {
            map.put("info","验证失败");
        }
        return map;
    }

    //发送手机验证码
    public HashMap<String, Object> sendPhoneCode(String phone, HttpServletRequest req) throws IOException, HTTPException {
        Phone phone1 = new Phone();
        String code = phone1.getCode(phone);
        System.out.println("---------------code-------------"+code);
        HashMap<String, Object> map =new HashMap<String, Object>();
        HttpSession session = req.getSession();
        if (code==""||code==null){
            map.put("info","发送失败");
        }else {
            session.setAttribute("code",code);
            map.put("info","发送成功");
        }
        return map;
    }

    //手机登录
    public HashMap<String, Object> phoneLogin(Long phone, String phoneCode, HttpServletRequest req) {
        HashMap<String, Object> map =new HashMap<String, Object>();
       Employee flag = Emapper.selectByEmployeePhone(phone);
        HttpSession session = req.getSession();
        String code = session.getAttribute("code")+"";
        if (flag == null){
            User user = new User();
            if (phone==null){
                map.put("info","手机号码为空");
            }else {
                user.setuPhone(phone);
                User userflag = Umapper.selectUserByPhone(phone);
                if (userflag==null){
                    if (code.equals(phoneCode)){
                        user.setuName(String.valueOf(phone));
                        user.setuPassword(phoneCode);
                        int i = Umapper.insertSelective(user);
                        if (i>0){
                            User user1 = Umapper.selectUserByPhone(phone);
                            map.put("info","新用户您好");
                            map.put("user",user1);
                        }else {
                            map.put("info","创建用户失败");
                        }
                    }else {
                        map.put("info","验证失败");
                    }
                }else {
                        if (code.equals(phoneCode)){
                            map.put("info","登录成功");
                            map.put("user",userflag);
                        }else {
                            map.put("info","验证失败");
                        }
                    }
                }

            }else {
                if (code.equals(phoneCode)){
                    map.put("employee",flag);
                    map.put("info","恭喜你登录成功");
                }else {
                    map.put("info","验证失败");
                }
        }

        return map;
    }


}
